﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ServiceProcess;

namespace SharepointSolutionInstaller.Utils.RequiredChecks
{
    /// <summary>
    /// Checks if the Windows SharePoint Services Timer service is started.
    /// </summary>
    internal class TimerServiceCheck : SystemCheck
    {
        internal TimerServiceCheck() : base("TimerServiceCheck") { }

        protected override SystemCheckResult DoExecute()
        {
            try
            {
                ServiceController sc = new ServiceController("SPTimerV4");
                if (sc.Status == ServiceControllerStatus.Running)
                {
                    return SystemCheckResult.Success;
                }
                return SystemCheckResult.Error;

                //
                // LFN 2009-06-21: Do not restart the time service anymore. First it does
                // not always work with Windows Server 2008 where it seems a local 
                // admin may not necessarily be allowed to start and stop the service.
                // Secondly, the timer service has become more stable with WSS SP1 and SP2.
                //
                /*TimeSpan timeout = new TimeSpan(0, 0, 60);
                ServiceController sc = new ServiceController("SPTimerV3");
                if (sc.Status == ServiceControllerStatus.Running)
                {
                  sc.Stop();
                  sc.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
                }

                sc.Start();
                sc.WaitForStatus(ServiceControllerStatus.Running, timeout);

                return SystemCheckResult.Success;*/
            }

            catch (System.ServiceProcess.TimeoutException ex)
            {
            
            }

            catch (Win32Exception ex)
            {
            
            }

            catch (InvalidOperationException ex)
            {
               
            }

            return SystemCheckResult.Inconclusive;
        }

        protected override bool CanRun
        {
            get { return IsWSSInstalled; }
        }
    }
}
